local M = { }

local log = require("log"):new("svc_login")
local pb = require("protobuf")
local User = require("user")
local user_mgr = require("user_mgr")
-- DEL local login_mgr = require("login.login_manager")

local test_server = { '222.73.63.209' }
local test_port = { 27017 }
local test_user = 'test'
local test_password = '123@123'
local test_db = 'giantserver_test'
local test_collection = 't_accounts'
local test_options = ""

local mygamedb = "mygame_inst"
local mdb = require("mongodb"):new(mygamedb, test_server, test_port, test_db, test_user, test_password, test_options)

log:debug("loading service...")

-- Return LoginResponse.
local function login(ctx, request)
    local rpc_clt_id = ctx:get_rpc_clt_id()
    log:info("Login. account=%q rpc_clt_id=%u", request.account, rpc_clt_id)
    if user_mgr.get_count() > 3000 then
        -- Todo: config max_user
        local resp = { result = "ERR_SERVER_FULL" }
        c_rpc.reply_to(ctx, pb.encode("rpc.LoginResponse", resp))
        return
    end

    --[[ 暂时禁用manager登录验证，待客户端实现。
	如需测试，
	先运行testClient执行test.loginManager()命令模拟用户登录到服务器Manager
	再用猫狗大战客户端（同样的用户名）去登录服务器（30秒超时）

	registerdata = login_mgr.get_center_register_data(request.account)
	if not registerdata then
		log:debug("Login not register manager . account=%q rpc_clt_id=%u", request.account, rpc_clt_id)
		local resp = {result = "ERR_M_NOT_LOGIN_MANAGER"}
		c_rpc.reply_to(ctx, pb.encode("rpc.LoginResponse", resp))
		return
	end
	]]

    -- query all the values in the namespace 'test.values'
    log:debug("mongodb query test begin ")
    -- XXX mdb:query(test_db, test_collection, {account=request.account},'', function (results)
    results = { }

    log:debug("mongodb query test end ")
    local found = false
    for i = 1, #results, 1 do
        -- 无效判断密码 ，这个由平台来决定	此账号已经存在于 mongodb中
        local result = results[i]
        local old_clt_id = user_mgr.get_rpc_clt_id(request.account)
        if old_clt_id and rpc_clt_id ~= old_clt_id then
            -- 此账号已经登陆
            log:info("Kick multi-login client. CltId=" .. old_clt_id)
            c_rpc.disconnect(old_clt_id);
            -- 断开连接
        end
        found = true;
    end

    log:info("db:count: %d", #results)

    user = User:new(rpc_clt_id, request.account)
    if not found then
        -- 说明原来数据库中 没有, 需要插入到数据库中
        -- insert a value into the namespace 'test.values'
        mdb:insert(test_db, test_collection, user)
    end

    if user_mgr.insert(user) then
        local resp = { result = "OK" }
        c_rpc.reply_to(ctx, pb.encode("rpc.LoginResponse", resp))
        -- delete center register data
        -- DEL login_mgr.delete_center_register_data(request.account)
        return
    end

    local resp = { result = "ERR_MULTI_LOGIN" }
    c_rpc.reply_to(ctx, pb.encode("rpc.LoginResponse", resp))
    -- XXX end)
end  -- login()

function M.Login(ctx, content)
    log:info("Logining...")
    local req = pb.decode("rpc.LoginRequest", content)
    login(ctx, req)
end  -- Login()

local function logout(ctx, request)
    log:info("Logout. account=%q rpc_clt_id=%u", request.account, ctx:get_rpc_clt_id())
end

function M.Logout(ctx, content)
    local req = pb.decode("rpc.LogoutRequest", content)
    c_rpc.disconnect(ctx:get_rpc_clt_id())
    -- 断开连接
end

require("rpc_request_handler").register_service("rpc.Login", M)
-- XXX rpc.Logout undefined?
require("rpc_request_handler").register_service("rpc.Logout", M)
return M 
